
var adfFormEngine = {
    
    util : {
        getHtmlAttr : function(attrMap){
            var strInfo = "";
            $.each(attrMap,function(i,item){
                strInfo += item.key +"=\"" + item.value + "\" ";
            });

            if(strInfo !== ""){
                strInfo = strInfo.substr(0, strInfo.length - 1);
            }

            return strInfo;
        },
        setHtmlAttr : function(attrObj,key,value){
            if(key in attrObj && value !== ""){
                attrObj[key] = value;
            }
        },
        // 拷贝指定的key 从一个对象到另外一个对象
        copyHtmlAttr:function(attrObj,fromObj,fromKey,targetKey){

            if(typeof(targetKey) === "undefined"){
                targetKey = fromKey;
            }

            if(fromKey in fromObj && fromObj[fromKey] !== ""){
                attrObj[targetKey] = fromObj[fromKey];
            }
        },
        getCtrlEvent : function(ctrl){
            var htmlInfo = "";
            $.each(ctrl.events,function(i,item){
                
            })

        },
        getHtmlAttr : function(attrObj){
            
            console.log("attrObj",attrObj);
            var attrInfo = "";
            var classInfo = "";
            var styleInfo = "";
            var attrList = {style:"",class:""};
            
            for(var key in attrObj){

                var value = attrObj[key];

                if(key === "class"){
                    
                    var arrClass = attrObj.class.split(",");

                    $.each(arrClass,function(i,tmpClass){
                        if(tmpClass !== "undefined" && tmpClass !== ""){
                            if(classInfo.indexOf(tmpClass+" ") === -1){
                                classInfo +=tmpClass + " ";
                            }
                        }
                    });

                    attrList.class = classInfo.trim();
                } else if (key === "style"){

                    for(var tmpKey in attrObj.style){
                        styleInfo += tmpKey + ":" + attrObj.style[tmpKey] +";"
                    }
                    attrList.style = styleInfo;
                    
                } else {
                    attrList[key] = value;
                }
            }

            var ret = "";
            for(var key in attrList){
                var value = attrList[key];
                if(attrList[key] !== ""){
                    ret += key + "=\"" + value + "\" ";
                }
            }

            return ret;
        }
    },


    
    // 标准控件定义
    stdCtrlList : [
        {
            ctrlName:"按钮",
            ctrlType:"button"
        },

        {
            ctrlName:"容器",
            ctrlType:"div"
        },
        {
            ctrlName:"Layui标签",
            ctrlType:"layuiFormLabel"
        },
        {
            ctrlName:"layui行",
            ctrlType:"layuiRow"
        },
        {
            ctrlName:"layui表单行",
            ctrlType:"layuiFormItem"
        },
        {
            ctrlName:"layui输入框",
            ctrlType:"layuiInput"
        },
        {
            ctrlName:"layui输入包裹框",
            ctrlType:"layuiInputWrap"
        },
        {
            ctrlName:"layui卡片",
            ctrlType:"layuiCard"
        },
        {
            ctrlName:"layui进度条",
            ctrlType:"layuiProgress"
        },
        {
            ctrlName:"layui日期",
            ctrlType:"layuiDatetime"
        },
        {
            ctrlName:"layui徽章",
            ctrlType:"layuiBadge"
        },
        {
            ctrlName:"图片",
            ctrlType:"img"
        },
        {
            ctrlName:"layui按钮",
            ctrlType:"layuiButton"
        },
        {
            ctrlName:"layui下拉框",
            ctrlType:"layuiSelect"
        },
        {
            ctrlName:"layui多行文本",
            ctrlType:"layuiTextarea"
        },
        {
            ctrlName:"layui多选框",
            ctrlType:"layuiCheckboxGroup"
        },
        {
            ctrlName:"layui单选框",
            ctrlType:"layuiRadioGroup"
        },
        {
            ctrlName:"layui静态表格",
            ctrlType:"layuiTable"
        },
        {
            ctrlName:"layui选项卡",
            ctrlType:"layuiTab"
        },
        {
            ctrlName:"layui数据表格",
            ctrlType:"layuiDataTable"
        },
    ],

    //控件定义
    ayCtrl : {
        childPropList:"form,layuiForm,layuiFormItem,div,layuiTabItem,layuiRowCol,layuiCardHeader,layuiCardBody,auCtrl",
        itemPropList:"layuiTab",
        colsPropList:"layuiRow",
        ctrlDefine:[
            {
                ctrlType:"button",
                id:"",
                class:"",
                events:[
                    {caption:"单击",type:"click",funcName:"",content:""}
                ],
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                caption:"按钮"
            },
            {
                ctrlType:"div",
                id:"",
                class:"",
                type:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:[],
                childs:[]
            },
            {
                ctrlType:"form",
                id:"",
                class:"",
                events:[],
                childs:[]
            },
            {
                ctrlType:"layuiButton",
                id:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:[],
                caption:"按钮"
            },
            {
                ctrlType:"layuiInput",
                id:"",
                class:"",
                name:"",
                value:"",
                layIgnore:"",
                layVerify:"",
                layFilter:"",
                layVertype:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                placeholder:"请输入文字",
                events:[]
            },
            {
                ctrlType:"layuiInputWrap",
                id:"",
                class:"",
                name:"",
                value:"",
                layIgnore:"",
                layVerify:"",
                layFilter:"",
                layVertype:"",
                spit:true,
                layAffix:"search",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                placeholder:"请输入文字",
                events:[]
            },
            {
                ctrlType:"layuiCard",
                id:"",
                class:"",
                header:{
                    ctrlType:"layuiCardHeader",
                    id:"",
                    class:"",
                    style:{
                        textAlign:"",
                        width:"",
                        height:""
                    },
                    events:[],
                    childs:[]
                },
                body:{
                    ctrlType:"layuiCardBody",
                    id:"",
                    class:"",
                    style:{
                        textAlign:"",
                        width:"",
                        height:""
                    },
                    events:[],
                    childs:[]
                },
                events:[]
            },
            {
                ctrlType:"layuiCardHeader",
                id:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:[],
                childs:[]
            },
            {
                ctrlType:"layuiCardBody",
                id:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:[],
                childs:[]
            },
            {
                ctrlType:"layuiProgress",
                id:"",
                class:"",
                theme:"",
                size:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                layPercent:"50%",
                layShowPercent:true,
                events:[]
            },
            {
                ctrlType:"layuiDatetime",
                id:"",
                class:"",
                name:"",
                value:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                layIgnore:"",
                layVerify:"",
                layFilter:"",
                layVertype:"",
                placeholder:"请输入文字",
                events:[]
            },
            {
                ctrlType:"layuiBadge",
                id:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                caption:"1",
                color:"layui-bg-blue",
                events:[]
            },
            {
                ctrlType:"img",
                id:"",
                class:"",
                src:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                alt:"图片",
                events:[]
            },
            {
                ctrlType:"layuiFormLabel",
                id:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                caption:"Form标签",
                events:[]
            },
            {
                ctrlType:"layuiTextarea",
                id:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                name:"",
                placeholder:"请输入文字",
                events:[]
            },
            {
                ctrlType:"layuiRow",
                id:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:[],
                cols:[
                    {
                        ctrlType:"layuiRowCol",
                        id:"",
                        class:"",
                        mdNum:2,
                        style:{
                            textAlign:"",
                            width:"",
                            height:""
                        },
                        events:[],
                        childs:[]
                    },
                ]
            },
            {
                ctrlType:"layuiInputBlock",
                id:"",
                class:"",
                events:[],
                childs:[]
            },
            {
                ctrlType:"layuiFormItem",
                id:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:[],
                childs:[]
            },
            {
                ctrlType:"layuiRowCol",
                id:"",
                class:"",
                mdNum:2,
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:[],
                childs:[]
            },
            {
                ctrlType:"layuiTab",
                id:"",
                class:"",
                events:[],
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                items:[{
                    ctrlType:"layuiTabItem",
                    id:"",
                    class:"",
                    caption:"选项1",
                    selected:true,
                    style:{
                        textAlign:"",
                        width:"",
                        height:""
                    },
                    events:[],
                    childs:[]
                },
                {
                    ctrlType:"layuiTabItem",
                    id:"",
                    class:"",
                    caption:"选项2",
                    selected:false,
                    style:{
                        textAlign:"",
                        width:"",
                        height:""
                    },
                    events:[],
                    childs:[]
                },
                {
                    ctrlType:"layuiTabItem",
                    id:"",
                    class:"",
                    caption:"选项3",
                    selected:false,
                    style:{
                        textAlign:"",
                        width:"",
                        height:""
                    },
                    events:[],
                    childs:[]
                }
                
                ]
            },
            {
                ctrlType:"layuiTabItem",
                id:"",
                class:"",
                caption:"选项1",
                selected:true,
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:[],
                childs:[]
            },
            {
                ctrlType:"layuiSelect",
                id:"",
                name:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                layFilter:"",
                events:[],
                items:[{name:"选项1",value:"选项1"},{name:"选项2",value:"选项2"}]
            },
            {
                ctrlType:"layuiCheckboxGroup",
                id:"",
                name:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                laySkin:"none",
                events:[],
                items:[{title:"选项1"},{title:"选项2"}]
            },
            {
                ctrlType:"layuiRadioGroup",
                id:"",
                name:"",
                class:"",
                laySkin:"none",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:[],
                items:[{title:"选项1"},{title:"选项2"}]
            },
            {
                ctrlType:"layuiTable",
                id:"",
                rowNum:2,
                colNum:3,
                class:"",
                laySkin:"none",
                events:[],
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                items:[]
            },
            {
                ctrlType:"layuiTableCell",
                id:"",
                class:"",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:[],
                childs:[]
            },
            {
                ctrlType:"layuiDataTable",
                id:"",
                data:{},
                elem:"",
                width:"",
                url:"",
                height:"",
                class:"",
                page:true,
                laySkin:"none",
                style:{
                    textAlign:"",
                    width:"",
                    height:""
                },
                events:{
                    click:null,
                },
                cols:[[]]
            },
        ],
        getCtrlDefine:function(type){

            var entity ;
            $.each(adfFormEngine.ayCtrl.ctrlDefine,function(i,item){
                if(item.ctrlType === type){
                    entity = $.extend({},item);
                    return false;
                }
            });

            console.log("当前的结构是",entity);
            return entity;
        },
        
        //根据类型得到通用的属性
        // 这里还有子属性，比如字体，颜色 等属性还有
        // 去除其他
        getCommonHtmlAttr: function(define,extName){
            if(typeof(define) === "undefined"){
                return "";
            }

            if(typeof(extName) === "undefined"){
                extName = "";
            }

            var arrExtName = extName.split(",");

            var attrInfo = "";

            var classInfo="";
            console.log("commhtml attr",define);
            if(define.hasOwnProperty("class")){
                console.log("commhtml attr has class");
                classInfo = define.class;
                if(classInfo.length > 0){
                    classInfo +=" ctrlItem";
                }
                else{
                    classInfo = "ctrlItem";
                }
                console.log("commhtml attr has classInfo",classInfo);
                var canPutList = "div, form, layuiForm,layuiRow, layuiRowCol, layuiTabItem,layuiFormItem,layuiTableCell,layuiCardHeader,layuiCardBody,Ctrl";
                if(canPutList.indexOf(define.ctrlType+",") > -1){
                    classInfo +=" canPut"
                }
            }

            if(classInfo.length > 0){
                classInfo = "class=\"" + classInfo + "\"";
            }
            console.log("commhtml attr has classInfo",classInfo);
            // classInfo 独立处理

            // 其他属性处理
            var htmlAttrList = "id,class,name,lay-filter,src,alt,title,href"
            for(var key in define){
                if(key !== "class" && typeof(define[key]) !=="object"){
                    if(htmlAttrList.indexOf(key+",") > -1){
                        if(arrExtName.indexOf(key) === -1){
                            attrInfo += key+"=\"" + define[key] + "\" ";
                        }
                        
                    }
                }
            }

            attrInfo +=" " + classInfo;
            console.log("commhtml attr has attrInfo",attrInfo);

            return attrInfo;
        },
        renderCtrl:function(define){
        },
        getButton:function(config){


            var attrObj ={};
            attrObj["adf-ctrl"] = "button";
            attrObj.id = config.id;
            attrObj.class = config.type + ",ctrlItem," + config.class
            attrObj.style = {};
            if(typeof(config.style.textAlign) !== "undefined"){
                attrObj.style["text-align"] = config.style.textAlign;
            }

            console.log("div attrObj",attrObj);
            
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            
            var caption = config.caption;
            if(typeof(caption) === "undefined"){
                caption = "按钮";
            }

            var html = "<button "+attrInfo+">"+caption+"</button>";
            return html;
        },
        getDiv:function(config){
            // type 可以是layui-inline layui-input-block 等
            var attrObj ={};
            attrObj["adf-ctrl"] = "div";
            attrObj.id = config.id;
            attrObj.class = config.type + ",ctrlItem,canPut," + config.class
            attrObj.style = {};
            if(typeof(config.style.textAlign) !== "undefined"){
                attrObj.style["text-align"] = config.style.textAlign;
            }
            adfFormEngine.util.copyHtmlAttr(attrObj.style,config.style,"width");

            console.log("div attrObj",attrObj);
            
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            var html = "<div "+attrInfo+" adf-ctrl=\"div\"></div>";
            return html;
        },
        getLayuiForm:function(config){

            var classInfo = config.class;
            if(classInfo !== ""){
                config.class = "layui-form" + classInfo;
            }
            else{
                config.class = "layui-form";
            }

            var attrInfo = adfFormEngine.ayCtrl.getCommonHtmlAttr(config);
            var html = "<div "+attrInfo+" adf-ctrl=\"layuiForm\"></div>";
            return html;
        },
        getLayuiFormLabel:function(config){
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiFormLabel";
            attrObj.id = config.id;
            attrObj.class = "layui-form-label,ctrlItem," + config.class

            var caption = config.caption;
            if(typeof(caption) === "undefined"){
                caption = "";
            }

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            var html = "<label "+attrInfo+">"+caption+"</label>";
            return html;
        },
        getLayuiFormItem:function(config){

            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiFormItem";
            attrObj.id = config.id;
            attrObj.class = "layui-form-item,ctrlItem,canPut," + config.class

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);

            var html = "<div "+attrInfo+"></div>";
            return html;
        },
        getLayuiRow:function(config){

            
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiRow";
            attrObj.id = config.id;
            attrObj.class = "layui-row,ctrlItem," + config.class;

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            var pre = "<div "+attrInfo+">";
            var cols = "";
            $.each(config.cols,function(i,item){
                cols += adfFormEngine.ayCtrl.getLayuiRowCol(item);
            });
            var suffix = "</div>";
            var html = pre + cols + suffix;
            return html;
        },
        getLayuiRowCol:function(config){
            
            var mdNum = config.mdNum;
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiRowCol";
            attrObj.id = config.id;
            attrObj.class = "layui-col-md"+mdNum+",ctrlItem,canPut," + config.class;

            attrObj.style = {};
            if(typeof(config.style.textAlign) !== "undefined"){
                attrObj.style["text-align"] = config.style.textAlign;
            }
            
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            var html = "<div "+attrInfo+"></div>";
            return html;
        },
        getLayuiInput:function(config){

            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiInput";
            attrObj.id = config.id;
            attrObj.name = config.name;
            attrObj.value = config.value;
            attrObj["lay-ignore"] = config.layIgnore;
            attrObj["lay-vertype"] = config.layVertype;
            attrObj["lay-verify"] = config.layVerify;
            attrObj["lay-filter"] = config.layFilter;
            attrObj.placeholder = config.placeholder;
            
            attrObj.class = "layui-input,ctrlItem"

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            
            var html = "<input "+attrInfo+" />";
            return html;
        },
        getLayuiInputWrap:function(config){

            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiInputWrap";
            attrObj.id = config.id;
            attrObj.class = "layui-input-wrap,ctrlItem," + config.class;
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            var attrInputObj ={};
            attrInputObj.name = config.name;

            attrInputObj.value = config.value;
            attrInputObj.type = "text";
            attrInputObj.class = "layui-input";
            attrInputObj["lay-ignore"] = config.layIgnore;
            attrInputObj["lay-vertype"] = config.layVertype;
            attrInputObj["lay-verify"] = config.layVerify;
            attrInputObj["lay-affix"] = config.layAffix;
            attrInputObj["lay-filter"] = config.layFilter;
            attrInputObj.placeholder = config.placeholder;
            

            adfFormEngine.util.copyHtmlAttr(attrInputObj,config,"layAffix","lay-affix");
        
            var inputWrapAttrInfo = adfFormEngine.util.getHtmlAttr(attrInputObj);
           
            
            var html = "<div "+attrInfo+"><input "+inputWrapAttrInfo+" /></div>";
            return html;
        },
        getLayuiCard:function(config){

            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiCard";
            attrObj.id = config.id;
            attrObj.class = "layui-card,ctrlItem"

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);

            var pre = "<div "+attrInfo+">";
            var header = adfFormEngine.ayCtrl.getLayuiCardHeader(config.header);
            var body = adfFormEngine.ayCtrl.getLayuiCardBody(config.body);
            var suffix = "</div>";
            var html = pre + header + body + suffix;
            return html;
        },
        getLayuiCardHeader:function(config){
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiCardHeader";
            attrObj.id = config.id;
            attrObj.class = "layui-card-header,ctrlItem,canPut"

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            
            var html = "<div "+attrInfo+"></div>";
            return html;
        },
        getLayuiCardBody:function(config){
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiCardHeader";
            attrObj.id = config.id;
            attrObj.class = "layui-card-body,ctrlItem,canPut"

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            
            var html = "<div "+attrInfo+"></div>";
            return html;
        },
        getLayuiProgress:function(config){

            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiProgress";
            attrObj.id = config.id;

            attrObj.class = "layui-progress,ctrlItem" ;

            
            //主题
            var themeInfo = "";
            if(typeof(config.theme) !=="undefined" && config.theme !== ""){
                themeInfo = " "+config.theme+"";
            }

            // 大小
            if(typeof(config.size) !=="undefined"){
                attrObj.class += "," + config.size;
            }

            attrObj.class += "," + config.class;
            //进度
            var layPercentInfo = "";
            if(typeof(config.layPercent) !=="undefined"){
                layPercentInfo = "lay-percent=\""+config.layPercent+"\"";
            }

            if(typeof(config.layShowPercent) !=="undefined"){
                attrObj["lay-showpercent"] = config.layShowPercent;
            }
            
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);


            var pre = "<div "+attrInfo+">";
            var bar = "<div class=\"layui-progress-bar"+themeInfo+"\" "+layPercentInfo+"  ></div>";
            var suffix = "</div>"
            var html = pre + bar + suffix;
            return html;
        },
        getLayuiDatetime:function(config){
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiDatetime";
            attrObj.id = config.id;
            attrObj.name = config.name;
            attrObj.value = config.value;
            attrObj["lay-ignore"] = config.layIgnore;
            attrObj["lay-vertype"] = config.layVertype;
            attrObj["lay-verify"] = config.layVerify;
            attrObj["lay-filter"] = config.layFilter;
            attrObj.placeholder = config.placeholder;
            
            attrObj.class = "layui-input,ctrlItem"

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            
            var html = "<input "+attrInfo+" />";
            return html;
        },
        getLayuiBadge:function(config){

            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiBadge";
            attrObj.id = config.id;
            attrObj.class = "layui-badge";
            if(typeof(config.color) !== "undefined" && config.color != ""){
                attrObj.class +="," + config.color;
            }

            attrObj.class += ",ctrlItem," + config.class;

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);


            var caption = config.caption;
            if(typeof(caption) === "undefined"){
                caption = "";
            }

           
            var html = "<span "+attrInfo+">"+caption+"</span>";
            return html;
        },
        getImg:function(config){
            var attrObj ={};
            attrObj["adf-ctrl"] = "img";
            attrObj.id = config.id;
            attrObj.class = "";
            if(typeof(config.alt) !== "undefined" && config.alt != ""){
                attrObj.alt =config.alt;
            }
            if(typeof(config.src) !== "undefined" && config.src != ""){
                attrObj.src =config.src;
            }

            attrObj.class += ",ctrlItem," + config.class;

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            
            var html = "<img "+attrInfo+" />";
            return html;
        },
        getLayuiButton:function(config){
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiButton";
            attrObj.id = config.id;
            attrObj.class = "layui-btn,ctrlItem," + config.theme +"," + config.border + "," + config.size +"," + config.class;
            var caption = config.caption;
            if(typeof(caption) === "undefined"){
                caption = "";
            }
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            
            var html = "<button "+attrInfo+">"+caption+"</button>";
            return html;
        },
        getLayuiTextarea:function(config){
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiTextarea";
            attrObj.id = config.id;
            attrObj.class = "layui-textarea,ctrlItem," + config.class;
            adfFormEngine.util.copyHtmlAttr(attrObj,config,"name");
            adfFormEngine.util.copyHtmlAttr(attrObj,config,"placeholder");

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            var pre = "<textarea "+attrInfo+" >";
            var suffix = "</textarea>";
            var html = pre + suffix;
            return html;
        },
        getLayuiSelect:function(config){

            //外围属性
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiSelect";
            attrObj.id = config.id;
            attrObj.class = "ctrlItem," + config.class;
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);

            //select属性
            var layuiSelectAttr = {};
            adfFormEngine.util.copyHtmlAttr(layuiSelectAttr,config,"name");
            adfFormEngine.util.copyHtmlAttr(layuiSelectAttr,config,"layFilter","lay-filter");
            var layuiSelectAttrAttrInfo = adfFormEngine.util.getHtmlAttr(layuiSelectAttr);
            
            var pre = "<div "+attrInfo+"><select "+layuiSelectAttrAttrInfo+">";
            var items = "";
            if(typeof(config.items) !== "undefined"){
                $.each(config.items,function(i,item){
                    items += "<option value="+item.value+">"+item.name+"</option>" 
                });
            }
            var suffix = "</select></div>";

            var html = pre + items + suffix;
            return html;
        },
        getLayuiCheckboxGroup:function(config){
            //外围属性
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiCheckboxGroup";
            attrObj.id = config.id;
            attrObj.class = "ctrlItem," + config.class;
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);

            //select属性
            var layuiSelectAttr = {};
            adfFormEngine.util.copyHtmlAttr(layuiSelectAttr,config,"name");
            var layuiSelectAttrAttrInfo = adfFormEngine.util.getHtmlAttr(layuiSelectAttr);
            
            var pre = "<div "+attrInfo+">";
            var items = "";
            if(typeof(config.items) !== "undefined"){
                $.each(config.items,function(i,item){
                    var checkedInfo = "";
                    if(item.checked){
                        checkedInfo ="checked";
                    }
                    var valueInfo="";
                    if(typeof(item.value) !=="undefined"){
                        valueInfo = " value=\""+item.value+"\"";
                    }

                    var layFilterInfo = "";
                    if(typeof(item.layFilter) !=="undefined"){
                        valueInfo = " lay-filter=\""+item.layFilter+"\"";
                    }

                    var laySkin = "";
                    if(typeof(item.laySkin) !=="undefined"){
                        valueInfo = " lay-skin=\""+item.laySkin+"\"";
                    }

                    items += "<input type=\"checkbox\" name=\""+name+"\" title="+item.title+""+checkedInfo+valueInfo+" />";
                });
            }
            var suffix = "</div>";

            var html = pre + items + suffix;
            return html;
        },
        getLayuiRadioGroup:function(config){
            //外围属性
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiRadioGroup";
            attrObj.id = config.id;
            attrObj.class = "ctrlItem," + config.class;
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);

            //select属性
            var layuiSelectAttr = {};
            var name = config.name;
            //adfFormEngine.util.copyHtmlAttr(layuiSelectAttr,config,"name");
            //var layuiSelectAttrAttrInfo = adfFormEngine.util.getHtmlAttr(layuiSelectAttr);


            
            var pre = "<div "+attrInfo+">";
            var items = "";
            if(typeof(config.items) !== "undefined"){
                $.each(config.items,function(i,item){
                    var checkedInfo = "";
                    if(item.checked){
                        checkedInfo ="checked";
                    }
                    var valueInfo="";
                    if(typeof(item.value) !=="undefined"){
                        valueInfo = " value=\""+item.value+"\"";
                    }

                    var layFilterInfo = "";
                    if(typeof(item.layFilter) !=="undefined"){
                        valueInfo = " lay-filter=\""+item.layFilter+"\"";
                    }

                    var laySkin = "";
                    if(typeof(item.laySkin) !=="undefined"){
                        valueInfo = " lay-skin=\""+item.laySkin+"\"";
                    }

                    items += "<input type=\"radio\" name=\""+name+"\" title="+item.title+""+checkedInfo+valueInfo+" />";
                });
            }
            var suffix = "</div>";

            var html = pre + items + suffix;
            return html;
        },
        getLayuiTable:function(config){
            
            console.log("getLayuiTable config",config);
            //根据行列得到单元格
            function findCell(rowIndex, colIndex){
                var entity = config.items.find(x=>{return x.rowIndex === rowIndex && x.colIndex===colIndex});
                return entity;
            }

            //外围属性
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiTable";
            attrObj.id = config.id;
            attrObj.class = "ctrlItem," + config.class;
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            
            var rowNum = config.rowNum;
            var colNum = config.colNum;
            
            var pre = "<div "+attrInfo+"><table class=\"layui-table\">";
            
            var rows = "";
            for(var i=1; i<=rowNum; i++){
                var row="<tr>";
                for(var j=1; j<=colNum; j++){
                    var cell = findCell(i, j);
                    row += adfFormEngine.ayCtrl.getLayuiTableCell(cell)    
                }
                row += "</tr>";
                rows += row;
            }

            var suffix = "</table></div>";

            var html = pre + rows + suffix;
            return html;
        },
        getLayuiDataTable:function(config){

            //外围属性
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiDataTable";
            attrObj.id = config.id;
            attrObj.class = "ctrlItem," + config.class;
            //attrObj.layFilter = attrObj.id +"_filter";
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            // table 属性
            var attrTableObj = {};
            attrTableObj.id = attrObj.id +"_table";
            attrTableObj["lay-filter"] = attrObj.layFilter;
            attrTableObj.class = "layui-hide";
            //attrTableObj.elem = attrObj.id +"_table";
            //attrObj.cols = JSON.stringify(config.cols);

            var attrTableInfo = adfFormEngine.util.getHtmlAttr(attrTableObj);
            
            
           
            
            var pre = "<div "+attrInfo+"><table "+attrTableInfo+">";
            
            var suffix = "</table></div>";

            var html = pre + suffix;
            return html;
        },
        getLayuiTableCell:function(config){

            //外围属性
            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiTableCell";
            attrObj.id = config.id;
            attrObj.class = "ctrlItem,canPut," + config.class;
            attrObj.style = {};

            adfFormEngine.util.copyHtmlAttr(attrObj.style,config.style,"textAlign","text-align");
            adfFormEngine.util.copyHtmlAttr(attrObj.style,config.style,"width");
            adfFormEngine.util.copyHtmlAttr(attrObj.style,config.style,"height");

            console.log("getLayuiTableCell attrInfo",attrObj);

            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);

            

            var pre = "<td "+attrInfo+">";
            var suffix = "</td>";

            var html = pre + suffix;
            return html;
        },
        getLayuiTabItem:function(config){

            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiTabItem";
            attrObj.id = config.id;
            attrObj.class = "layui-tab-item,ctrlItem,canPut";
            if(config.selected){
                attrObj.class += ",layui-show";
            }
            attrObj.class += "," + config.class;

            attrObj.style = {};
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);
            var html = "<div "+attrInfo+"></div>";
            return html;
        },
        getLayuiTab:function(config){

            var attrObj ={};
            attrObj["adf-ctrl"] = "layuiTab";
            attrObj.id = config.id;
            attrObj.class = "layui-tab,ctrlItem,canPut";
            if(config.selected){
                attrObj += ",layui-show";
            }
            attrObj.class += "," + config.class;

            attrObj.style = {};
            var attrInfo = adfFormEngine.util.getHtmlAttr(attrObj);

            var pre = "<div "+attrInfo+" adf-ctrl=\"layuiTab\">";

            //构造title的头部
            var tabtitlePre = "<ul class=\"layui-tab-title\">";
            var tabtitlesItems = "";
            var index=0;
            $.each(config.items,function(i,item){
                var selectedInfo = "";
                if(item.selected){
                    selectedInfo = "class=\"layui-this\"";
                }
                var layId = index++;
                tabtitlesItems += "<li "+selectedInfo+" lay-id=\""+layId+"\">"+item.caption+"</li>";
            });
            var tabtitleSuffix = "</ul>"

            var tabtitleHtml = tabtitlePre + tabtitlesItems + tabtitleSuffix;


            // body部分
            var tabContentPre = "<div class=\"layui-tab-content\">";
            var tabContentItems = "";
            var index=0;
            $.each(config.items,function(i,item){
                console.log("tab item",item);
                tabContentItems += adfFormEngine.ayCtrl.getLayuiTabItem(item);
            });
            var tabContentSuffix = "</div>"

            var tabContentHtml = tabContentPre + tabContentItems + tabContentSuffix;

            var suffix = "</div>"
            var html = pre + tabtitleHtml + tabContentHtml + suffix;
            return html;
        }
        

    },

    //具体表单的定义
    ayForm : {
    ctrlMaxId:0,
    selectedElemId:"",
    selectedCtrlDefine :{},
    selectedCtrlEvent:{},
    CtrlList:[],
    formStruct:{id:"designArea",ctrlType:"layuiForm",childs:[]},
    eventDetailDlgId : -1,
    getNewCtrlId : function(){
        adfFormEngine.ayForm.ctrlMaxId++;
        return "el" + adfFormEngine.ayForm.ctrlMaxId;
    },
    getFormStuct : function(){

        var treeObj = [];
        function getChild(id){

            var obj = adfFormEngine.ayForm.getCtrlObjectById(id);
            var ctrlType = obj.ctrlType;
            // 表示是child的属性
            var node = {};
            node.id = id;
            node.title = id + "[" +ctrlType +"]";
            node.children=[];
            
            if(adfFormEngine.ayCtrl.childPropList.indexOf(obj.ctrlType+",") > -1){
               
                console.log("当前是childs");

                $.each(obj.childs,function(i,item){
                    var o = getChild(item.id);
                    node.children.push(o);
                });

            }

            if(adfFormEngine.ayCtrl.itemPropList.indexOf(obj.ctrlType+",") > -1){
                console.log("items");
               $.each(obj.items,function(i,item){
                   var o = getChild(item.id);
                   node.children.push(o);
               });

            }

            if(ctrlType === "layuiCard"){

                console.log("layui card ", obj);
                var newNode = {};
                newNode.id = obj.header.id;
                newNode.title = obj.header.id + "[" +obj.header.ctrlType +"]";
                newNode.children = [];
                $.each(obj.header.childs,function(i,item){
                   var o = getChild(item.id);
                   newNode.children.push(o);
               });
                node.children.push(newNode);

                var newNode2 = {};
                newNode2.id = obj.body.id;
                newNode2.title = obj.body.id + "[" +obj.body.ctrlType +"]";
                newNode2.children = [];
                $.each(obj.body.childs,function(i,item){
                   var o = getChild(item.id);
                   newNode2.children.push(o);
               });
                node.children.push(newNode2);
            }

            //对此特殊处理
            if(ctrlType === "layuiRow"){
                $.each(obj.cols,function(i,item){
                   var o = getChild(item.id);
                   node.children.push(o);
               });
               
            }


           return node;

        }

        var ret = getChild("designArea");

        //初始化树
        var tree = layui.tree;
        tree.render({
            elem: '#formStructTree',
            data: ret.children,
            showLine: true,
            click:function(obj){
                //点击事件
                // 得到当前对像的id,并重值当前的按钮

                console.log("tree data",obj)
                adfFormEngine.ayForm.selectedElemId = obj.data.id;
                adfFormEngine.ayForm.selectedCtrlDefine = adfFormEngine.ayForm.getCtrlObjectById(obj.data.id); 

            }
        });

        

    },

    setCtrlEvents:function(ctrl){

        console.log("设置当前的控件事件",ctrl);
        var tpl = $("#CommonEventTpl").html();

        var html = layui.laytpl(tpl).render(ctrl);

        $("#ctrlEventList").html(html);

    },

    // 返回对象以及当前的路径
    getCtrlObjectById : function(id){
        //通过递归的方式换到控件json对象
        function doFind(obj,targetId){
            for (var key in obj) {
                if (key === "id") {
                    if (obj.id === targetId) {
                        return obj;
                    }
                }

                if (typeof obj[key] === "object" && obj[key] !== null) {
                        var result = doFind(obj[key], targetId);
                        if (result) {
                            return result;
                        }
                }
            }
            return null;
        }
        var obj = doFind(adfFormEngine.ayForm.formStruct,id);
        return obj;
    },
    deleteCtrlObjectById : function(id){
        //通过递归的方式换到控件json对象
        function deleteById(obj, targetId) {
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if (typeof obj[key] === 'object' && obj[key] !== null) {
                        // 递归处理嵌套对象
                        deleteById(obj[key], targetId);

                        // 如果嵌套对象被清空，删除父对象的键
                        if (Object.keys(obj[key]).length === 0) {
                            delete obj[key];
                        }
                    } else if (key === 'id' && obj[key] === targetId) {
                        // 如果当前对象是目标对象，删除它
                        delete obj[key];
                        console.log("已经删除了");
                        console.log(adfFormEngine.ayForm.formStruct);
                    }
                }
                }
        }
        deleteById(adfFormEngine.ayForm.formStruct,id);
    },
    //开始初始化
    init:function(){
        // 初始化左侧
        new Sortable(document.getElementById('leftNav'), {
            group: {
                name: 'shared', // 组名
                pull: "clone",     // 允许拖出元素
                put: false       // 允许放入元素
            },
            sort:false,
            animation: 150,

        }); 

        this.initLefNavCtrl();
        this.initDesignSortable();
        this.initCtrlSort();
        this.initEvent();

    },

    initLefNavCtrl:function(){
        $("#leftNav").html("");
        $(adfFormEngine.stdCtrlList).each(function(i,item){
            var button = "<button class=\"ctrl "+item.ctrlType+"\" ctrl-type=\""+item.ctrlType+"\">"+item.ctrlName+"</button>";
            $("#leftNav").append(button);
        });
    },

    setCtrlProp : function(ctrl){

        if($("#"+ctrl.ctrlType+"Tpl").length === 0){
            layer.msg("模板不存在");
            return;
        }

        var ctrlType = ctrl.ctrlType;

        var objData = {};
        objData.ctrl = ctrl;

        //html 样式通用的设置

        //标准事件
        adfFormEngine.ayForm.setCtrlEvents(ctrl);


        if(ctrlType === "layuiButton"){
            objData.themeList = [
                {caption:"默认",value:""}
                ,{caption:"蓝色",value:"layui-bg-blue"}
                ,{caption:"橙色",value:"layui-bg-orange"}
                ,{caption:"红色",value:"layui-bg-red"}
                ,{caption:"紫色",value:"layui-bg-purple"}
                ,{caption:"禁用",value:"layui-btn-disabled"}
            ];
            objData.borderList = [
                {caption:"普通",value:"layui-border"}
                ,{caption:"主色",value:"layui-border-green"}
                ,{caption:"蓝色",value:"layui-border-blue"}
                ,{caption:"橙色",value:"layui-border-orange"}
                ,{caption:"红色",value:"layui-border-red"}
                ,{caption:"紫色",value:"layui-border-purple"}
            ];
            objData.sizeList = [
                {caption:"默认",value:""}
                ,{caption:"大",value:"layui-btn-lg"}
                ,{caption:"小",value:"layui-btn-sm"}
                ,{caption:"迷你",value:"layui-btn-xs"}
            ];
        }

        if(ctrlType === "layuiRow"){
            //
        }

        if(ctrlType === "layuiProgress"){
            //
            objData.themeList = [
            {caption:"默认",value:""}
            ,{caption:"蓝色",value:"layui-bg-blue"}
            ,{caption:"橙色",value:"layui-bg-orange"}
            ,{caption:"红色",value:"layui-bg-red"}
            ,{caption:"紫色",value:"layui-bg-purple"}
            ,{caption:"禁用",value:"layui-btn-disabled"}
            ];

            objData.sizeList = [
                {caption:"无",value:""}
                ,{caption:"大",value:"layui-progress-big"}
            ];
        }
        
        if(ctrlType === "layuiBadge"){
            //
            objData.themeList = [
            {caption:"无",value:""}
            ,{caption:"蓝色",value:"layui-bg-blue"}
            ,{caption:"橙色",value:"layui-bg-orange"}
            ,{caption:"绿色",value:"layui-bg-green"}
            ,{caption:"红色",value:"layui-bg-red"}
            ,{caption:"表色",value:"layui-bg-cyan"}
            ,{caption:"紫色",value:"layui-bg-purple"}
            ,{caption:"黑色",value:"layui-bg-black"}
            ];
        }

        if(ctrlType === "layuiSelect" || ctrlType === "layuiCheckboxGroup"|| ctrlType === "layuiRadioGroup"){
            objData.itemInfo = JSON.stringify(ctrl.items);
        }


        if(ctrlType === "layuiRowCol"){
            //
            objData.mdNumList = [
                {caption:"1",value:"1"}
                ,{caption:"2",value:"2"}
                ,{caption:"3",value:"3"}
                ,{caption:"4",value:"4"}
                ,{caption:"5",value:"5"}
                ,{caption:"6",value:"6"}
                ,{caption:"7",value:"7"}
                ,{caption:"8",value:"8"}
                ,{caption:"9",value:"9"}
                ,{caption:"10",value:"10"}
                ,{caption:"11",value:"11"}
                ,{caption:"12",value:"12"}
            ];
        }

        if(ctrlType === "div"){
            //
            objData.typeList = [
                {caption:"无",value:""}    
                ,{caption:"layui-inline",value:"layui-inline"}
                ,{caption:"layui-input-block",value:"layui-input-block"}
            ];
        }

        var tplContent = "<div id=\"globalProp\">";
        tplContent += $("#"+ctrlType+"Tpl").html();
        tplContent += "<div class=\"layui-row\"><button class=\"layui-btn\" id=\"btnSaveCtrlProp\">保存</button></div>";
        tplContent += "</div>";

        var commonAttrTpl = $("#CommonAttrTpl").html();
        tplContent = tplContent.replace("<!--CommonAttr-->",commonAttrTpl)

        var commonEventTpl = $("#CommonEventTpl").html();
        tplContent = tplContent.replace("<!--CommonEvent-->",commonEventTpl)

        console.log("objData",objData);
        var retHtml = layui.laytpl(tplContent).render(objData);

        layer.open({
            type: 1,
            title:"控件属性配置",
            offset: 'r',
            anim: 'slideLeft', // 从右往左
            area: ['600px', '90%'],
            shade: 0,
            shadeClose: true,
            fixed:true,
            content: retHtml,
            success: function(layero, index, that){
                console.log("成功打开");
                
                var element = layui.element;
                layui.form.render("select");
                element.render('collapse', "tplInfo");
                
            }
        });
    },

    /**
        根据配置保存控件，并对form表单进行渲染
    */
    saveCtrlProp: function(ctrlDefine){

        console.log("saveCtrlProp ctrlDefine",ctrlDefine);
        var ctrlType = ctrlDefine.ctrlType;
        var ctrlId = ctrlDefine.id;

        //根据控件类型，生成对应的html
        if(ctrlType === "layuiButton"){
            var html = adfFormEngine.ayCtrl.getLayuiButton(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        } 
        else if(ctrlType === "button"){
            var html = adfFormEngine.ayCtrl.getButton(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        } 
        else if(ctrlType === "layuiFormLabel"){
            var html = adfFormEngine.ayCtrl.getLayuiFormLabel(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        }
        else if(ctrlType === "layuiSelect"){
            var html = adfFormEngine.ayCtrl.getLayuiSelect(ctrlDefine);
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        } 
        else if(ctrlType === "img"){
            var html = adfFormEngine.ayCtrl.getImg(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        } 
        else if(ctrlType === "layuiProgress"){
            var html = adfFormEngine.ayCtrl.getLayuiProgress(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        } 
        else if(ctrlType === "layuiCheckboxGroup"){
            var html = adfFormEngine.ayCtrl.getLayuiCheckboxGroup(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        } 
        else if(ctrlType === "layuiRadioGroup"){
            var html = adfFormEngine.ayCtrl.getLayuiRadioGroup(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        } 
        else if(ctrlType === "layuiBadge"){
            var html = adfFormEngine.ayCtrl.getLayuiBadge(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        }
        else if(ctrlType === "layuiInput"){
            var html = adfFormEngine.ayCtrl.getLayuiInput(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        }
        else if(ctrlType === "layuiInputWrap"){
            var html = adfFormEngine.ayCtrl.getLayuiInputWrap(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        }
        else if(ctrlType === "layuiDatetime"){
            var html = adfFormEngine.ayCtrl.getLayuiDatetime(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        }
        else if(ctrlType === "layuiDataTable"){
            var html = adfFormEngine.ayCtrl.getLayuiDataTable(ctrlDefine)
            $("#" + adfFormEngine.ayForm.selectedElemId ).after(html).remove();
        } 
        else if (ctrlType === "layuiRow"){
            var ctrlHtml = adfFormEngine.ayCtrl.getLayuiRow(ctrlDefine)
            var colHtmlInfo = "";
            
            //循环每个列的信息
            $.each(ctrlDefine.cols,function(i,item){
                var colHtml = adfFormEngine.ayCtrl.getLayuiRowCol(item)
                //当前控件的内部的html
                var formHtmlOfChild = $("#"+item.id).html();
                var $colHtml = $(colHtml);
                $colHtml.html(formHtmlOfChild);
                var newHtml = $colHtml.prop("outerHTML");
                colHtmlInfo += newHtml;
            })
            $("#" + ctrlId ).html(colHtmlInfo);
           
        }
        else if (ctrlType === "layuiTable"){
            var ctrlHtml = adfFormEngine.ayCtrl.getLayuiTable(ctrlDefine)

            var $ctrlHtml = $(ctrlHtml);
            var colHtmlInfo = "";
            
            //循环每个列的信息
            $.each(ctrlDefine.items,function(i,item){

                //当前控件的内部的html
                var formHtmlOfChild = "";
                if($("#"+item.id).length > 0){
                    formHtmlOfChild = $("#"+item.id).html();

                    $($ctrlHtml.find("#"+item.id)[0]).html(formHtmlOfChild);
                }
            })
            var newHtml = $ctrlHtml.prop("outerHTML");
            $("#" + ctrlId ).after(newHtml).remove();

            //初始化控件排序
            adfFormEngine.ayForm.initCtrlSort();
        }
        else if (ctrlType === "layuiRowCol"){
            var ctrlHtml = adfFormEngine.ayCtrl.getLayuiRowCol(ctrlDefine)
            //当前控件的内部的html
            var formHtmlOfChild = $("#"+ctrlId).html();
            var $ctrlHtml = $(ctrlHtml);
            $ctrlHtml.html(formHtmlOfChild);
            var newHtml = $ctrlHtml.prop("outerHTML");
            $("#" + ctrlId ).after(newHtml).remove();
        }
        else if (ctrlType === "div"){
            var ctrlHtml = adfFormEngine.ayCtrl.getDiv(ctrlDefine)
            //当前控件的内部的html
            var formHtmlOfChild = $("#"+ctrlId).html();
            var $ctrlHtml = $(ctrlHtml);
            $ctrlHtml.html(formHtmlOfChild);
            var newHtml = $ctrlHtml.prop("outerHTML");
            $("#" + ctrlId ).after(newHtml).remove();
        }
        else if (ctrlType === "layuiCardHeader"){
            var ctrlHtml = adfFormEngine.ayCtrl.getLayuiCardHeader(ctrlDefine)
            //当前控件的内部的html
            var formHtmlOfChild = $("#"+ctrlId).html();
            var $ctrlHtml = $(ctrlHtml);
            $ctrlHtml.html(formHtmlOfChild);
            var newHtml = $ctrlHtml.prop("outerHTML");
            $("#" + ctrlId ).after(newHtml).remove();
        }
        else if (ctrlType === "div"){
            var ctrlHtml = adfFormEngine.ayCtrl.getLayuiCardBody(ctrlDefine)
            //当前控件的内部的html
            var formHtmlOfChild = $("#"+ctrlId).html();
            var $ctrlHtml = $(ctrlHtml);
            $ctrlHtml.html(formHtmlOfChild);
            var newHtml = $ctrlHtml.prop("outerHTML");
            $("#" + ctrlId ).after(newHtml).remove();
        }
        else if (ctrlType === "layuiTableCell"){
            var ctrlHtml = adfFormEngine.ayCtrl.getLayuiTableCell(ctrlDefine)
            //当前控件的内部的html
            var formHtmlOfChild = $("#"+ctrlId).html();
            var $ctrlHtml = $(ctrlHtml);
            $ctrlHtml.html(formHtmlOfChild);
            var newHtml = $ctrlHtml.prop("outerHTML");
            $("#" + ctrlId ).after(newHtml).remove();
        }
        else if (ctrlType === "layuiTab"){
            console.log("layuiTab ctrlDefine",ctrlDefine);
            var ctrlHtml = adfFormEngine.ayCtrl.getLayuiTab(ctrlDefine)

            var $ctrlHtml = $(ctrlHtml);
            var colHtmlInfo = "";
            
            //循环每个列的信息
            $.each(ctrlDefine.items,function(i,item){

                //当前控件的内部的html
                var formHtmlOfChild = "";
                if($("#"+item.id).length > 0){
                    formHtmlOfChild = $("#"+item.id).html();       
                    $($ctrlHtml.find("#"+item.id)[0]).html(formHtmlOfChild);                 
                }
                
            })
            var newHtml = $ctrlHtml.prop("outerHTML");
            $("#" + ctrlId ).after(newHtml).remove();
            form.render();
            //初始化控件排序
            adfFormEngine.ayForm.initCtrlSort();
        }
        else if (ctrlType === "layuiTabItem"){
            var ctrlHtml = adfFormEngine.ayCtrl.getLayuiTabItem(ctrlDefine)
            //当前控件的内部的html
            var formHtmlOfChild = $("#"+ctrlId).html();
            var $ctrlHtml = $(ctrlHtml);
            $ctrlHtml.html(formHtmlOfChild);
            var newHtml = $ctrlHtml.prop("outerHTML");
            $("#" + ctrlId ).after(newHtml).remove();
        }

        //重新加载
        adfFormEngine.ayForm.LoadScript(ctrlDefine);
        
    },

    /** 
    得到一个控件的下所有的子对象
    */
    getParentIdByCtrlId : function(ctrlId){

        console.log("ctrlId",ctrlId);
        var lstInfo = $("#"+ctrlId).parents().get();

        console.log("lstInfo",lstInfo);
        var parentId = "";
        $.each(lstInfo,function(i,item){
            
            if(typeof($(item).attr("adf-ctrl")) !== "undefined"){
                parentId = $(item).attr("id");
                return false;
            }
        })
        
        return parentId;

    },

    /**
    根据html的id 下所有的子元素信息来更新object对象的信息
    
    */
    deleteChildObject : function(ctrlId,childId){
        // 当前对象
        var ctrlObject = adfFormEngine.ayForm.getCtrlObjectById(ctrlId);

        //var childList = $("#"+ctrlId).children();
        if(adfFormEngine.ayCtrl.childPropList.indexOf(ctrlObject.ctrlType+",") > -1){
            
            var index = ctrlObject.childs.findIndex(x=>x.id===childId);

            if(index >= 0){
                ctrlObject.childs.splice(index,1);
            }
        }
        if(adfFormEngine.ayCtrl.itemPropList.indexOf(ctrlObject.ctrlType+",") > -1){
            
            var index = ctrlObject.items.findIndex(x=>x.id===childId);

            if(index >= 0){
                ctrlObject.items.splice(index,1);
            }
        }

        if(adfFormEngine.ayCtrl.colsPropList.indexOf(ctrlObject.ctrlType+",") > -1){
            
            var index = ctrlObject.cols.findIndex(x=>x.id===childId);
            if(index >= 0){
                ctrlObject.cols.splice(index,1);
            }
        }


    },

    log:function(content){
        console.log(content);
    },
    setFormJson:function(){
        $("#ctrlDefine").val(JSON.stringify(adfFormEngine.ayForm.formStruct))
    },
    // 打对话框
    showDlg:function(title,tplContent,successFunc){
        return layer.open({
            type: 1,
            title:title,
            area: ['80%', '80%'],
            content: tplContent,
            success: function(layero, index, that){
                console.log("成功打开");
                successFunc(layero,index,that);
            }
        });
    },
    initEvent:function(){

        //增加当前控件事件

        $("body").on("click","#btnCtrlEventAdd",function(){
            var event = {};
            event.type = "";
            event.content = "";
            event.caption = "新事件";
            event.funcName = "function()";
            event.doCmd = "add";

            var tpl = $("#EventEditTpl").html();

            var html = layui.laytpl(tpl).render(event);
                
            adfFormEngine.ayForm.eventDetailDlgId = adfFormEngine.ayForm.showDlg("代码",html,function(){

                var editor = ace.edit("myCode");
                editor.setTheme("ace/theme/monokai");
                editor.session.setMode("ace/mode/javascript");
                editor.session.setValue(event.content);

               // 监听内容变化
                editor.session.on("change", function(delta) {
                    console.log("内容变化了:", delta);
                    event.content = editor.getValue();

                    $($("#CtrlEventDetail").find("input[id='content']")[0]).val(editor.getValue());
                    adfFormEngine.ayForm.setFormJson();
                });

                // 添加保存快捷键
                editor.commands.addCommand({
                    name: "save",
                    bindKey: { win: "Ctrl-S", mac: "Command-S" },
                    exec: function(editor) {
                        const code = editor.getValue();
                        localStorage.setItem("savedCode", code);
                        console.log("内容已保存");
                    }
                });

                var element = layui.element;
                layui.form.render("select");
            });

        })

        //修改
        $("body").on("click",".btnCtrlEventModify",function(){

            var that = this;
            var eventType = $(that).parent().find("input[name='type']").val();

            var event = adfFormEngine.ayForm.selectedCtrlDefine.events.find(x=>x.type===eventType);
            if(typeof(event) ==="undefined"){
                layer.msg("不存在事件");
                return;
            }

            event.doCmd = "modify";

            var tpl = $("#EventEditTpl").html();
            var html = layui.laytpl(tpl).render(event);
                
            adfFormEngine.ayForm.eventDetailDlgId = adfFormEngine.ayForm.showDlg("代码",html,function(){

                var editor = ace.edit("myCode");
                editor.setTheme("ace/theme/monokai");
                editor.session.setMode("ace/mode/javascript");
                editor.session.setValue(event.content);

               // 监听内容变化
                editor.session.on("change", function(delta) {
                    console.log("内容变化了:", delta);
                    $($("#CtrlEventDetail").find("input[id='content']")[0]).val(editor.getValue());
                    adfFormEngine.ayForm.setFormJson();
                });

                // 添加保存快捷键
                editor.commands.addCommand({
                    name: "save",
                    bindKey: { win: "Ctrl-S", mac: "Command-S" },
                    exec: function(editor) {
                        $($("#CtrlEventDetail").find("input[id='content']")[0]).val(editor.getValue());
                    }
                });

                var element = layui.element;
                layui.form.render("select");
            });

        })

        //删除
        $("body").on("click",".btnCtrlEventDelete",function(){

            var that = this;
            var eventType = $(that).parent().find("input[name='type']").val();

            var index = adfFormEngine.ayForm.selectedCtrlDefine.events.findIndex(x=>x.type===eventType);
            if(index > -1){
                adfFormEngine.ayForm.selectedCtrlDefine.events.splice(index,1);
            }

            //重新初始化事件列表
            adfFormEngine.ayForm.setCtrlEvents(adfFormEngine.ayForm.selectedCtrlDefine);
        })

        //弹出代码编辑
        $("body").on("click","#btnCtrlEventSave",function(){
            var that = this;
            var eventType = $($("#CtrlEventDetail").find("input[id='type']")[0]).val();
            var caption = $($("#CtrlEventDetail").find("input[id='caption']")[0]).val();
            var funcName = $($("#CtrlEventDetail").find("input[id='funcName']")[0]).val();
            var eventType = $($("#CtrlEventDetail").find("input[id='type']")[0]).val();
            var doCmd = $($("#CtrlEventDetail").find("input[id='doCmd']")[0]).val();
            var content = $($("#CtrlEventDetail").find("input[id='content']")[0]).val();
            
            // 增加
            if(doCmd === "add"){
                
                var event = adfFormEngine.ayForm.selectedCtrlDefine.events.find(x=>x.type===eventType);
                console.log("save",event);
                if(typeof(event) !== "undefined"){
                    layer.msg("事件已存在");
                }

                var tmpEvent = {};
                tmpEvent.type = eventType;
                tmpEvent.caption = caption;
                tmpEvent.funcName = funcName;
                tmpEvent.content = content;

                console.log("tmpEvent",tmpEvent);

                adfFormEngine.ayForm.selectedCtrlDefine.events.push(tmpEvent);

                
            }

            //修改
            if(doCmd === "modify"){
                var event = adfFormEngine.ayForm.selectedCtrlDefine.events.find(x=>x.type===eventType);
                if(event === "undefined"){
                    layer.msg("事件不存在");
                }
                event.caption = caption;
                event.funcName = funcName;
                event.content = content;
            }

            // 得新初始化控件
            adfFormEngine.ayForm.setCtrlEvents(adfFormEngine.ayForm.selectedCtrlDefine);

            adfFormEngine.ayForm.setFormJson();
           
            // 关闭最后 一个弹窗
            console.log("关闭....");
            //var index = layer.getFrameIndex("代码"); // 先得到当前 iframe 层的索引
            //console.log("index",index);
            //layer.close(index); // 再执行关闭
            console.log("adfFormEngine.ayForm.eventDetailDlgId",adfFormEngine.ayForm.eventDetailDlgId);
            layui.layer.close(adfFormEngine.ayForm.eventDetailDlgId);
            
        });

        $("body").on("click","#btnGetStruct",function(){
            adfFormEngine.ayForm.getFormStuct();
        });

        $("body").on("click","#btnMarkCtrlItem",function(){
            adfFormEngine.ayForm.markCtrlItem();
        });

        $("body").on("mouseover",".ctrlItem",function(e){
            $(".overlay-layer").hide();
            
            var that = this;
            $(this).addClass("ctrlItemOver");

           var ctrlId = $(that).attr("id");
           var tipCtrlId = "tip-" + ctrlId;

           if($("#"+tipCtrlId).length > 0){
                $("#"+tipCtrlId).remove();
           }

           var left = $("#"+ctrlId).offset().left;
            //left +=ctrlIndex;
            var top = $("#"+ctrlId).offset().top;
            var styleInfo = "style=\"left:"+left+"px;top:"+top+"px;\"";
            var layer = "<div id=\""+tipCtrlId+"\" class=\"overlay-layer selectCtrl\" "+styleInfo+">+</div>";
            console.log("left, top",left,top);
            $("body").append(layer);

           $("#"+tipCtrlId).show();
            

            // 给当前的ctrlItem 加上控件图标
            //var ctrlLayer = "<div class=\"overlay-layer\">+</div>" ;
           // $(that).append(ctrlLayer);
            e.stopPropagation();

            //console.log("e",e);
        })

        $("body").on("mouseout",".ctrlItem",function(){
            $(this).removeClass("ctrlItemOver")
        })

        //删除当前的元素
        $("body").on("click","#btnDeleteSelectedElem",function(e){
            var that = this;
            var ctrlId = adfFormEngine.ayForm.selectedElemId;
            console.log("ctrlId",ctrlId);

            if(ctrlId === ""){
                return;
            }

            // 从对象中进行删除
            var parentCtrlId = adfFormEngine.ayForm.getParentIdByCtrlId(ctrlId);
            adfFormEngine.ayForm.deleteChildObject(parentCtrlId,ctrlId);

            // 从html中删除
            $("#"+ctrlId).remove();

            adfFormEngine.ayForm.setFormJson();
        })

        //通过元素路径来选择当前的控件
        $("body").on("click","#elemInfo button",function(e){
            var that = this;
            var ctrlId = $(that).attr("data");
            console.log("ctrlId",ctrlId);

            if(ctrlId === ""){
                return;
            }

            //重新设置当前的选择的控件

            adfFormEngine.ayForm.selectedElemId = ctrlId;
            adfFormEngine.ayForm.selectedCtrlDefine = adfFormEngine.ayForm.getCtrlObjectById(ctrlId); 
            
            //得到选择的控件下一级所有子控件

            
            
        })

        $("body").on("click",".ctrlItemxx",function(e){
            var that = this;
            adfFormEngine.ayForm.selectedElemId = $(this).attr("id");
            adfFormEngine.ayForm.selectedCtrlDefine = adfFormEngine.ayForm.getCtrlObjectById(adfFormEngine.ayForm.selectedElemId);
            $(this).toggleClass("ctrlItemClick")

            // 递归找到当前控件的路径
            var parentPath = $(that).parents().get().reverse();
            var pathInfo = "路径:";
            $.each(parentPath,function(i,item){
                var tagName = $(item).prop("tagName");
                var ctrlId = $(item).attr("id");
                var ctrlType = $(item).attr("adf-ctrl");
                if(typeof(ctrlId) === "undefined"){
                    ctrlId = "";
                }
                if(typeof(ctrlType) === "undefined"){
                    ctrlType = "";
                }
                pathInfo += "<button class='layui-btn layui-btn-xs' data='"+ctrlId+"'>"+tagName+"("+ctrlType+"["+ctrlId+"])"+"</button> > ";
            });

            if(pathInfo.length !== ""){
                pathInfo = pathInfo.substr(0,pathInfo.length-1);
            }

            $("#elemInfo").html(pathInfo);

            // 这里会阻止事件冒泡，影响layui原始控件的 tab 的切换
            

            if( typeof($(that).attr("adf-ctrl")) !== "undefined"){
                var ctrlLayer = "<div class=\"ctrlTip\">+</div>" ;
                //$(that).append(ctrlLayer);
            }
            
            //$(that).append(ctrlLayer);
            //console.log("e",e);
            //e.stopPropagation();
        })

        $("body").on("click",".selectCtrl",function(e){
            var that = this;
            adfFormEngine.ayForm.selectedElemId = $(this).attr("id").replace("tip-","");
            adfFormEngine.ayForm.selectedCtrlDefine = adfFormEngine.ayForm.getCtrlObjectById(adfFormEngine.ayForm.selectedElemId);
            $("#"+adfFormEngine.ayForm.selectedElemId).toggleClass("ctrlItemClick")

            // 递归找到当前控件的路径
            var parentPath = $("#"+adfFormEngine.ayForm.selectedElemId).parents().get().reverse();
            var pathInfo = "路径:";
            $.each(parentPath,function(i,item){
                var tagName = $(item).prop("tagName");
                var ctrlId = $(item).attr("id");
                var ctrlType = $(item).attr("adf-ctrl");
                if(typeof(ctrlId) === "undefined"){
                    ctrlId = "";
                }
                if(typeof(ctrlType) === "undefined"){
                    ctrlType = "";
                }
                pathInfo += "<button class='layui-btn layui-btn-xs' data='"+ctrlId+"'>"+tagName+"("+ctrlType+"["+ctrlId+"])"+"</button> > ";
            });

            //增加当前元素
            var currentCtrlId = adfFormEngine.ayForm.selectedElemId;
            var currentTagName = $("#" + adfFormEngine.ayForm.selectedElemId).prop("tagName");
            var currentCtrlType = adfFormEngine.ayForm.selectedCtrlDefine.ctrlType;
            pathInfo += "<button class='layui-btn layui-btn-xs' data='"+currentCtrlId+"'>"+currentTagName+"("+currentCtrlType+"["+currentCtrlId+"])"+"</button>";

            if(pathInfo.length !== ""){
                pathInfo = pathInfo.substr(0,pathInfo.length-1);
            }

            $("#elemInfo").html(pathInfo);

            
        })
        
        //用于增加相关的设置
        // 针对比如layuirow 中需要增加一列这样的计算
        $("body").on("click",".btnAddSetup",function(e){
            
            var ctrlType = adfFormEngine.ayForm.selectedCtrlDefine.ctrlType;
            var ctrlDefine = adfFormEngine.ayForm.selectedCtrlDefine;
            var ctrlId = adfFormEngine.ayForm.selectedCtrlDefine.id;

            var opId = $(this).attr("id");
            

            if(opId === "layuiRowAddCol"){
                console.log("对行增加列");
                // 表示是增加列
                var col = adfFormEngine.ayCtrl.getCtrlDefine("layuiRowCol");
                col.id = adfFormEngine.ayForm.getNewCtrlId();
                ctrlDefine.cols.push(col);

                $("#ctrlDefine").val(JSON.stringify(adfFormEngine.ayForm.formStruct));
                
                adfFormEngine.ayForm.saveCtrlProp(ctrlDefine);
            }

            if(opId === "layuiTabAddItem"){
                var tabItem = adfFormEngine.ayCtrl.getCtrlDefine("layuiTabItem");
                tabItem.id = adfFormEngine.ayForm.getNewCtrlId();
                tabItem.caption = "新选项";
                tabItem.selected = false;
                ctrlDefine.items.push(tabItem);

                $("#ctrlDefine").val(JSON.stringify(adfFormEngine.ayForm.formStruct));

                adfFormEngine.ayForm.saveCtrlProp(ctrlDefine);
            }

            //注册全部的排序
            adfFormEngine.ayForm.initCtrlSort();


            e.stopPropagation();
        })

        //属性input 编辑区变化

        /*
        DataTable测试的json
        [[
            {"field":"ID","title":"字段1","width":100},
            {"field":"MatterCateName","title":"字段2","width":300}
        ]]
        
        */

        $("body").on("change","#globalProp input,#globalProp select,#globalProp textarea",function(e){
            console.log("change",this);
            var that = this;
            var ctrlType = adfFormEngine.ayForm.selectedCtrlDefine.ctrlType;
            var ctrlDefine = adfFormEngine.ayForm.selectedCtrlDefine;
            var ctrlId = adfFormEngine.ayForm.selectedCtrlDefine.id;

            //通用样式定义
            var changeElemId = $(that).attr("id");
            var isDeal = 0;
            if(typeof(changeElemId) !=="undefined"){

                if(ctrlType === "layuiSelect" && changeElemId === "itemInfo"){
                    var itemInfo = $(that).val();
                    ctrlDefine.items = JSON.parse(itemInfo);
                    isDeal = 1;
                    
                } else if(ctrlType === "layuiCheckboxGroup" && changeElemId === "itemInfo"){
                    var itemInfo = $(that).val();
                    ctrlDefine.items = JSON.parse(itemInfo);
                    isDeal = 1;
                }
                else if(ctrlType === "layuiDataTable" && changeElemId === "cols"){
                    var colsInfo = $(that).val();
                    if(colsInfo === ""){
                        ctrlDefine.cols = [[]];
                    }
                    else{
                        ctrlDefine.cols = JSON.parse(colsInfo);
                    }
                    
                    isDeal = 1;
                }
                else if(ctrlType === "layuiRadioGroup" && changeElemId === "itemInfo"){
                    var itemInfo = $(that).val();
                    ctrlDefine.items = JSON.parse(itemInfo);
                    isDeal = 1;
                }
                else if(ctrlType === "layuiTable" && changeElemId === "rowNum"){
                   
                    var currentRowNum = parseInt($(that).val());
                    var oldRowNum = parseInt(ctrlDefine.rowNum);
                    var oldColNum = parseInt(ctrlDefine.colNum);
                    
                    if(currentRowNum > oldRowNum){
                        for(var i = oldRowNum+1; i<=currentRowNum; i++){
                            for(j=1; j<=oldColNum; j++){
                                var cell = adfFormEngine.ayCtrl.getCtrlDefine("layuiTableCell");
                                cell.id = adfFormEngine.ayForm.getNewCtrlId();
                                cell.rowIndex = i;
                                cell.colIndex = j;
                                ctrlDefine.items.push(cell);
                            }
                        }
                    }

                    ctrlDefine.rowNum = $(that).val();
                    isDeal = 1;
                }
                else if(ctrlType === "layuiTable" && changeElemId === "colNum"){
                    var currentColNum = parseInt($(that).val());
                    var oldRowNum = parseInt(ctrlDefine.rowNum);
                    var oldColNum = parseInt(ctrlDefine.colNum);
                    if(currentColNum > oldColNum){
                        for(var i = 1; i<=oldRowNum; i++){
                            for(j=oldColNum+1; j<=currentColNum; j++){
                                var cell = adfFormEngine.ayCtrl.getCtrlDefine("layuiTableCell");
                                cell.id = adfFormEngine.ayForm.getNewCtrlId();
                                ctrlDefine.items.push(cell);
                            }
                        }
                    }

                    ctrlDefine.colnu = $(that).val();
                    isDeal = 1;
                }
                else if(isDeal === 0){
                    if(changeElemId.indexOf("style-")>-1){
                        var styleKey = changeElemId.replace("style-","");
                        ctrlDefine.style[styleKey] = $(that).val();
                    }
                    else{
                        if(changeElemId in ctrlDefine){
                            ctrlDefine[changeElemId] = $(that).val();
                        }
                    }
                }
            }
            
            //其他特殊的定义
            console.log("保存后的定义是",ctrlDefine);
            adfFormEngine.ayForm.saveCtrlProp(ctrlDefine);
            layui.form.render();

        })

        //设置属性 btnSetCtrlProp 
        $("body").on("click","#btnSetCtrlProp",function(e){
           
            adfFormEngine.ayForm.selectedElemId = $("#"+adfFormEngine.ayForm.selectedElemId).attr("id");
            console.log("adfFormEngine.ayForm.selectedElemId",adfFormEngine.ayForm.selectedElemId);
            var ctrlDefine = adfFormEngine.ayForm.getCtrlObjectById(adfFormEngine.ayForm.selectedElemId)
            adfFormEngine.ayForm.setCtrlProp(ctrlDefine);
            adfFormEngine.ayForm.setCtrlEvents(ctrlDefine);
            e.stopPropagation();
       })

       $("body").on("click","#btnSaveCtrlProp",function(e){
           //adfFormEngine.ayForm.saveCtrlProp();
           layer.msg("应该使用input的change事件");
      })

        //保存控件定义

        $("body").on("click","#btnSaveCtrlDefine",function(){

            var html = adfFormEngine.ayForm.generateHtml();
            $("#resultHtml").val(html);
            //var config = JSON.parse($("#ctrlDefine").val());
            //var ctrlId = config.id;
            //插入新的html 同时将自身给移除掉
            //$("#"+ctrlId).after(html).remove();
        })
    },
    markCtrlItem:function(){

        var ctrlIndex = 0;
        $(".ctrlItem").each(function(i,item){
            ctrlIndex ++;

            console.log("item",item);

            var ctrlId = $(item).attr("id");
            var tipCtrlId = "tip-"+ctrlId;

            if($("#"+tipCtrlId).length === 0){
                var left = $("#"+ctrlId).offset().left;
                left +=ctrlIndex;
                var top = $("#"+ctrlId).offset().top;
                var styleInfo = "style=\"left:"+left+"px;top:"+top+"px;\"display:none;";
                var layer = "<div id=\""+tipCtrlId+"\" class=\"overlay-layer selectCtrl\" "+styleInfo+">+</div>";
                console.log("left, top",left,top);
                $("body").append(layer);
            }
            
        });
    },
    putEl:function(to,from,dragEl,event){

        console.log("from",from);
        console.log("to",to);
        console.log("dragEl",dragEl);
        console.log("event",event);

        //判断是否可以放入什么样的新元素
        if($(from.el).attr("id") === "leftNav"){
            //表示来源于左侧
            if(!($(to.el).hasClass("canPut"))){
                //console.log("无移入类，则不能移入");
                return false;
            }
        } 

        if($(from.el).hasClass("ctrlItem")){
            //
            if(!($(to.el).hasClass("canPut"))){
                //console.log("无移入类，则不能移入");
                return false;
            }

            
        }
        //console.log("允许拖入");
        return true;
    },
    pullEl:function(to,from,dragEl,event){
        var classInfo = $(dragEl).attr("class");
        
        var unCanPullList = "layuiCardHeader,layuiCardBody,unCtrl";
        var ctrlType = $(dragEl).attr("adf-ctrl");

        if(unCanPullList.indexOf(ctrlType+",") > -1){
            return false;
        }

        //console.log("允许拖出");



        return true;
    },
    addEl:function(evt){
        //在设计的元素在各个容器中互相拖动的
        if($(evt.from).attr("id") === "leftNav"){
            adfFormEngine.ayForm.addElFromLeftNav(evt);
        } 
        else{
            if($(evt.from).attr("adf-ctrl") !== ""){
                adfFormEngine.ayForm.addElFromDesign(evt);
            }
        }

        //对当前的表单进行渲染
        layui.form.render();

        return false;

    },
    updateEl : function(evt){
        console.log("update evt",evt);
        /*
        元素在同一个容器中进行移动的时候会触发当前的事件
        如果一个元素从一个容器中拖动到另外一个容器中，则会触发onAdd的事件
        */
        //元素更新时候的操作

        var from = evt.from;
        var to = evt.to;
        var fromId = $(from).attr("id");

        
       
        var itemPropList = "tab";
        var parentObject = adfFormEngine.ayForm.getCtrlObjectById(fromId);
        var childList = $("#"+fromId).children();
        //对是 childs 子成员按照 html的顺序进行重新排序
        if(adfFormEngine.ayCtrl.childPropList.indexOf(parentObject.ctrlType+",")>-1){
            var clonedChildren = JSON.parse(JSON.stringify(parentObject.childs));
            parentObject.childs=[];
          

                $.each(childList,function(i,item){
                    var childId = $(item).attr("id");                  
                    var cloneObj = clonedChildren.find(x=>x.id===childId);
                    parentObject.childs.push(cloneObj);
                });
        }
        //对是 items 子成员按照 html的顺序进行重新排序
        if(adfFormEngine.ayCtrl.itemPropList.indexOf(parentObject.ctrlType+",")>-1){
            var clonedChildren = JSON.parse(JSON.stringify(parentObject.items));
            parentObject.items=[];
          

                $.each(childList,function(i,item){
                    var childId = $(item).attr("id");                  
                    var cloneObj = clonedChildren.find(x=>x.id===childId);
                    parentObject.items.push(cloneObj);
                });
        }

        //对是 cols 子成员按照 html的顺序进行重新排序
        if(adfFormEngine.ayCtrl.colsPropList.indexOf(parentObject.ctrlType+",")>-1){
            var clonedChildren = JSON.parse(JSON.stringify(parentObject.cols));
            parentObject.cols=[];
            

                $.each(childList,function(i,item){
                    var childId = $(item).attr("id");                  
                    var cloneObj = clonedChildren.find(x=>x.id===childId);
                    parentObject.cols.push(cloneObj);
                });
        }

        $("#ctrlDefine").val(JSON.stringify(adfFormEngine.ayForm.formStruct));


    },
    addElFromDesign(evt){
       console.log("addElFromDesign",evt);

       /*需要完成的事情
       1、将对应的json对象，移入新的父级对象下
       
       */

       var targetContainer = evt.to;
        var targetId = $(targetContainer).attr("id");
        var targetObj = adfFormEngine.ayForm.getCtrlObjectById(targetId);
        console.log("targetObj",targetObj);
        if(typeof(targetObj) === "undefined" || targetObj === null){
            layer.msg("父级容器不存在");
            return;
        }
        var targetCtrlType = targetObj.ctrlType;

        //当前移动控件对应的对象
        var dragItem = evt.item;
        var dragItemCtrlType = $(dragItem).attr("adf-ctrl");
        var dragItemId = $(dragItem).attr("id");
        var dragItemObject = adfFormEngine.ayForm.getCtrlObjectById(dragItemId);

        //得到拖动对象的clone
        var dragItemObjectClone = JSON.parse(JSON.stringify(dragItemObject));
        
        var childList = $("#"+targetId).children();
        if(adfFormEngine.ayCtrl.childPropList.indexOf(targetObj.ctrlType+",") > -1){
            targetObj.childs.push(dragItemObjectClone);

            //根据当前的元素进行排序
            var clonedChildren = JSON.parse(JSON.stringify(targetObj.childs));
            targetObj.childs=[];
          

            $.each(childList,function(i,item){
                var childId = $(item).attr("id");                  
                var cloneObj = clonedChildren.find(x=>x.id===childId);
                targetObj.childs.push(cloneObj);
            });
        }
        if(adfFormEngine.ayCtrl.itemPropList.indexOf(targetObj.ctrlType+",") > -1){
            targetObj.items.push(dragItemObjectClone);

            //根据当前的元素进行排序
            var clonedChildren = JSON.parse(JSON.stringify(targetObj.items));
            targetObj.items=[];
        

            $.each(childList,function(i,item){
                var childId = $(item).attr("id");                  
                var cloneObj = clonedChildren.find(x=>x.id===childId);
                targetObj.items.push(cloneObj);
            });
        }

        //处理原有的容器

        var fromContainer = evt.from;
        var fromId = $(fromContainer).attr("id");
        var fromObj = adfFormEngine.ayForm.getCtrlObjectById(fromId);
        console.log("fromObj",fromObj);

        var fromChildList = $("#" + fromId).children();
        if(adfFormEngine.ayCtrl.childPropList.indexOf(fromObj.ctrlType+",") > -1){
           

            //根据当前的元素进行排序
            var clonedChildren = JSON.parse(JSON.stringify(fromObj.childs));
            fromObj.childs=[];
          

            $.each(fromChildList,function(i,item){
                var childId = $(item).attr("id");                  
                var cloneObj = clonedChildren.find(x=>x.id===childId);
                fromObj.childs.push(cloneObj);
            });
        }
        if(adfFormEngine.ayCtrl.itemPropList.indexOf(fromObj.ctrlType+",") > -1){
            
            //根据当前的元素进行排序
            var clonedChildren = JSON.parse(JSON.stringify(fromObj.items));
            fromObj.items=[];

            $.each(fromChildList,function(i,item){
                var childId = $(item).attr("id");                  
                var cloneObj = clonedChildren.find(x=>x.id===childId);
                fromObj.items.push(cloneObj);
            });
        }



        //将原有的进行删除掉
        //adfFormEngine.ayForm.deleteCtrlObjectById(dragItemId);

        $("#ctrlDefine").val(JSON.stringify(adfFormEngine.ayForm.formStruct));
    

    },
    addElFromLeftNav:function(evt){

        //这里需要完成的事情,得到控件的配置文件
        //这里是完成控件增加操作，使用的是默认，不涉及控件的参数调整

        var dragItem = evt.item;
        
        var targetContainer = evt.to;
        var targetId = $(targetContainer).attr("id");
        console.log("targetId",targetId);
        var targetObj = adfFormEngine.ayForm.getCtrlObjectById(targetId);
        if(typeof(targetObj) === "undefined" || targetObj == null){
            layer.msg("父级容器不存在");
            return;
        }

        console.log("目标容器的对象值",targetObj);



        var targetCtrlType = targetObj.ctrlType;            
        //原始先移除掉
        var ctrlType = $(dragItem).attr("ctrl-type");
        $(dragItem).remove();

        //将新的html进行解析
        var newHtml = "";

        //得到类型
        var define = adfFormEngine.ayCtrl.getCtrlDefine(ctrlType);

        if(typeof(define) === "undefined" || define.ctrlType === ""){
            layer.msg("不存在当前控件");
            return "";
        }

        var newHtml = "";
        if(ctrlType === "button"){
            console.log("加入Button");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            newHtml = adfFormEngine.ayCtrl.getButton(define);
        }
        if(ctrlType === "div"){
            console.log("加入div");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            newHtml = adfFormEngine.ayCtrl.getDiv(define);
        }
        if(ctrlType === "layuiRow"){
            console.log("加入layuiRow");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            $.each(define.cols,function(i,item){
                item.id = adfFormEngine.ayForm.getNewCtrlId();
            });

            newHtml = adfFormEngine.ayCtrl.getLayuiRow(define);
        }

        if(ctrlType === "layuiFormLabel"){
            console.log("layuiFormLabel");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            newHtml = adfFormEngine.ayCtrl.getLayuiFormLabel(define);
        }

        if(ctrlType === "layuiFormItem"){
            console.log("layuiFormItem");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            newHtml = adfFormEngine.ayCtrl.getLayuiFormItem(define);
        }

        if(ctrlType === "layuiRowCol"){
            console.log("加入layuiRowCol");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            
            newHtml = adfFormEngine.ayCtrl.getLayuiRowCol(define);
        }

        if(ctrlType === "layuiInput"){
            console.log("加入layuiInput");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            define.name = define.id;
            newHtml = adfFormEngine.ayCtrl.getLayuiInput(define);
        }

        if(ctrlType === "layuiInputWrap"){
            console.log("加入layuiInputWrap");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            define.name = define.id;
            newHtml = adfFormEngine.ayCtrl.getLayuiInputWrap(define);
        }

        if(ctrlType === "layuiCard"){
            console.log("加入layuiCard",define);
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            
            define.header.id = adfFormEngine.ayForm.getNewCtrlId();
            define.body.id = adfFormEngine.ayForm.getNewCtrlId();

            newHtml = adfFormEngine.ayCtrl.getLayuiCard(define);
        }

        if(ctrlType === "layuiProgress"){
            console.log("加入layuiProgress");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            newHtml = adfFormEngine.ayCtrl.getLayuiProgress(define);
        }

        if(ctrlType === "layuiDatetime"){
            console.log("加入layuiDatetime");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            define.class = "layui-input";
            define.name = define.id;
            newHtml = adfFormEngine.ayCtrl.getLayuiDatetime(define);
        }

        if(ctrlType === "layuiBadge"){
            console.log("加入layuiBadge");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            newHtml = adfFormEngine.ayCtrl.getLayuiBadge(define);
        }

        if(ctrlType === "img"){
            console.log("加入img");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            newHtml = adfFormEngine.ayCtrl.getImg(define);
        }

        if(ctrlType === "layuiButton"){
            console.log("加入layuiButton");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            newHtml = adfFormEngine.ayCtrl.getLayuiButton(define);
        }

        if(ctrlType === "layuiCheckboxGroup"){
            console.log("layuiCheckboxGroup");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            define.class = "layui-input";
            define.name = define.id;
            newHtml = adfFormEngine.ayCtrl.getLayuiCheckboxGroup(define);
        }

        
        if(ctrlType === "layuiRadioGroup"){
            console.log("layuiRadioGroup");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            define.name = define.id;
            newHtml = adfFormEngine.ayCtrl.getLayuiRadioGroup(define);
        }

        

        if(ctrlType === "layuiSelect"){
            console.log("layuiSelect");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            define.class = "";
            define.name = define.id;
            newHtml = adfFormEngine.ayCtrl.getLayuiSelect(define);
        }

        if(ctrlType === "layuiTextarea"){
            console.log("layuiTextarea");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            define.class = "";
            define.name = define.id;
            newHtml = adfFormEngine.ayCtrl.getLayuiTextarea(define);
        }

        if(ctrlType === "layuiTab"){
            console.log("layuiTab");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            define.class = "";

            console.log("define.items ",define.items);
            $.each(define.items,function(i,item){
                item.id = adfFormEngine.ayForm.getNewCtrlId();
            })

            newHtml = adfFormEngine.ayCtrl.getLayuiTab(define);
        }

        if(ctrlType === "layuiTable"){
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            define.class = "";

            var rowNum = define.rowNum;
            var colNum = define.colNum;

            //
            for(var i = 1; i<=rowNum; i++){
                for(var j=1; j<=colNum; j++){
                    var cell = adfFormEngine.ayCtrl.getCtrlDefine("layuiTableCell");
                    
                    cell.rowIndex = i;
                    cell.colIndex = j;
                    cell.id = adfFormEngine.ayForm.getNewCtrlId();
                    console.log("cell",cell);
                    define.items.push(cell);
                }
            }

            newHtml = adfFormEngine.ayCtrl.getLayuiTable(define);
        }

        if(ctrlType === "layuiDataTable"){
            console.log("layuiDataTable");
            define.id = adfFormEngine.ayForm.getNewCtrlId();
            define.class = "";

            newHtml = adfFormEngine.ayCtrl.getLayuiDataTable(define);
        }

        if(newHtml !== ""){

            $(targetContainer).append(newHtml);

            //如果是datatable 或者 其他需要给当前的控件加入动态脚本
            
            adfFormEngine.ayForm.LoadScript(define);

            //增加json中
            console.log("增加到json中",targetObj);
            

            var childList = $("#"+targetId).children();
            if(adfFormEngine.ayCtrl.childPropList.indexOf(targetObj.ctrlType+",") > -1){
                console.log("childList",childList);
                targetObj.childs.push(define);

                //根据当前的元素进行排序
                var clonedChildren = JSON.parse(JSON.stringify(targetObj.childs));
                targetObj.childs=[];
            

                $.each(childList,function(i,item){
                    var childId = $(item).attr("id");                  
                    var cloneObj = clonedChildren.find(x=>x.id===childId);
                    targetObj.childs.push(cloneObj);
                });

                console.log("adfFormEngine.ayForm.formStruct",adfFormEngine.ayForm.formStruct)
            }
            if(adfFormEngine.ayCtrl.itemPropList.indexOf(targetObj.ctrlType+",") > -1){
                targetObj.items.push(define);

                //根据当前的元素进行排序
                var clonedChildren = JSON.parse(JSON.stringify(targetObj.items));
                targetObj.items=[];
            

                    $.each(childList,function(i,item){
                        var childId = $(item).attr("id");                  
                        var cloneObj = clonedChildren.find(x=>x.id===childId);
                        targetObj.items.push(cloneObj);
                    });
            }

           
        }

        adfFormEngine.ayForm.initCtrlSort();

        $("#ctrlDefine").val(JSON.stringify(adfFormEngine.ayForm.formStruct));
        
        return "";

    },
    initCtrlSort:function(){
        var ctrlList = document.getElementsByClassName('ctrlItem');
        //console.log("ctrlList",ctrlList);

         // 遍历每个容器并初始化 Sortable
         Array.from(ctrlList).forEach(container => {
            new Sortable(container, {
                group: {
                        name: 'shared', // 组名
                        pull: function(to,from,dragEl,event){
                            return adfFormEngine.ayForm.pullEl(to,from,dragEl,event);
                        },     
                        // 允许拖入元素
                        put: function(to,from,dragEl){
                            return adfFormEngine.ayForm.putEl(to,from,dragEl);
                        }
                    },
                    draggable:".ctrlItem",
                    animation: 150,
                    sort:true,
                    forcePlaceholderSize: true,
                    onAdd:function(evt){
                        console.log("ctrlItem,有新的元素增加进来的事件...");
                        adfFormEngine.ayForm.addEl(evt);
                    },
                    onUpdate:function(evt){
                        console.log("ctrlItem on update ctrlItem ");
                        adfFormEngine.ayForm.updateEl(evt);
                        

                    }
            });
        });

    },
    //初始化设计区排序值
    initDesignSortable:function(){
        //初始化排序
        // 初始化右侧
        new Sortable(document.getElementById('designArea'), {
                    group: {
                        name: 'shared', // 组名
                        pull: true,     // 允许拖出元素
                        // 允许拖入元素
                        put: function(to,from,dragEl){
                            return adfFormEngine.ayForm.putEl(to,from,dragEl);
                        }
                    },
                    animation: 150,
                    draggable:".ctrlItem",
                    sort:true,
                    forcePlaceholderSize: true,
                    onAdd:function(evt){
                        //evt.stopPropagation();
                        adfFormEngine.ayForm.addEl(evt);
                    },
                    onUpdate:function(evt){
                        console.log("designArea on update ");
                        adfFormEngine.ayForm.updateEl(evt);
                    }
                }); 


    },
    LoadScript : function(define){

        var ctrlType = define.ctrlType;
        if(ctrlType === "layuiDataTable"){

            
            var config ={};
            config.elem = define.elem;
            if(config.elem === ""){
                config.elem = "#" +define.id+"_table";
            }
            if(define.url === ""){
                define.url = "/layui/sortable/data.json";
            }
            config.url = define.url;
            config.toolbar = define.toolbar;
            config.height = define.height;
            if(config.height === ""){
                config.height = "300";
            }
            config.cols = define.cols;
            config.page = define.page;
            if(config.page === ""){
                config.page = true;
            }

            console.log("datatable config",config);

            
            layui.table.render(config);
        }

        //日期类需要加载脚本
        if(ctrlType === "layuiDatetime"){
            var type = "date";
            if(typeof(define.type) !== "undefined"){
                type = define.type;
            }
            layui.laydate.render({
                elem :"#" + define.id,
                type:type
            });
        }

    },
    generateHtml : function(){
        //全局adfFormEngine.ayForm.formStruct 来整体形成html

        function doGen(obj){
            var objHtml = "";
            var ctrlType = obj.ctrlType;
            var elemId = adfFormEngine.ayCtrl.id;
            console.log("ctrlType",ctrlType);

            switch(ctrlType){
                case "layuiForm":
                    objHtml = adfFormEngine.ayCtrl.getLayuiForm(obj);
                break;
                case "layuiRow":
                    objHtml = adfFormEngine.ayCtrl.getLayuiRow(obj);
                break;

                case "layuiRowCol":
                    objHtml = adfFormEngine.ayCtrl.getLayuiRowCol(obj);
                break;
                case "layuiTextarea":
                    objHtml = adfFormEngine.ayCtrl.getLayuiTextarea(obj);
                break;
                

                case "layuiInput":
                    objHtml = adfFormEngine.ayCtrl.getLayuiInput(obj);
                break;

                case "layuiInputWrap":
                    objHtml = adfFormEngine.ayCtrl.getLayuiInputWrap(obj);
                break;

                case "layuiProgress":
                    objHtml = adfFormEngine.ayCtrl.getLayuiProgress(obj);
                break;

                case "layuiDatetime":
                    objHtml = adfFormEngine.ayCtrl.getLayuiDatetime(obj);
                break;

                case "layuiBadge":
                    objHtml = adfFormEngine.ayCtrl.getLayuiBadge(obj);
                break;
                case "img":
                    objHtml = adfFormEngine.ayCtrl.getImg(obj);
                break;
                case "layuiButton":
                    objHtml = adfFormEngine.ayCtrl.getLayuiButton(obj);
                break;
                case "layuiFormLabel":
                objHtml = adfFormEngine.ayCtrl.getLayuiFormLabel(obj);
            break;

                case "layuiCard":
                    objHtml = adfFormEngine.ayCtrl.getLayuiCard(obj);
                break;

                case "layuiCheckboxGroup":
                    objHtml = adfFormEngine.ayCtrl.getLayuiCheckboxGroup(obj);
                break;

                case "layuiRadioGroup":
                    objHtml = adfFormEngine.ayCtrl.getLayuiRadioGroup(obj);
                break;

                case "layuiTable":
                    objHtml = adfFormEngine.ayCtrl.getLayuiTable(obj);
                break;
                case "layuiTableCell":
                    objHtml = adfFormEngine.ayCtrl.getLayuiTableCell(obj);
                break;
                
                case "layuiDataTable":
                    objHtml = adfFormEngine.ayCtrl.getLayuiDataTable(obj);
                break;

                case "layuiSelect":
                    objHtml = adfFormEngine.ayCtrl.getLayuiSelect(obj);
                break;

                case "button":
                    objHtml = adfFormEngine.ayCtrl.getButton(obj);
                break;
                case "div":
                    objHtml = adfFormEngine.ayCtrl.getDiv(obj);
                break;
                default:
                    break;
            }

            console.log("控件主体html是:",objHtml);
            console.log("obj.childs",obj.childs);
            if(typeof(obj.childs) != "undefined" && obj.childs.length > 0){

                $.each(obj.childs,function(i,item){
                    console.log("item",item);
                    var chidlHtml = doGen(item);
                    //返回的html是
                    console.log("返回的html是",chidlHtml);
                    objHtml = $(objHtml).append(chidlHtml)[0].outerHTML;
                })
            }

            return objHtml;


        }

        var html = doGen(adfFormEngine.ayForm.formStruct);

        return html;


    }

}




}